<template>
  <div class="setting-flow-panel-container">
    <!-- 事件流程设置 -->
    <div class="setting-flow-axis-container">
      <div class="axis-header">{{$t('event.setting.serviceEventTypeSetting.flow.steps.flowSettingPanel.title1')}}</div>
      <div class="setting-flow-axis">
        <div
          class="flow-axis-step-box"
          :class="{
            close: flowAxisStepIsClose(key) && !flowAxisStepIsSystem(key),
          }"
          v-for="key in Object.keys(flowMap)"
          :key="key"
          @click="handleSelectFlowStep(key)"
        >
          <div class="flow-axis-step" :class="{ active: currFlow === key }">
            <div>
              <i :class="['iconfont', flowMap[key].icon]"></i>
              {{ flowMap[key].name }}
            </div>
            <div class="open-tag" v-if="flowAxisStepIsSystem(key) || !flowAxisStepIsClose(key)">
              {{$t('common.base.alreadyOpen')}}
            </div>
          </div>
          <div class="tooltip-wrap" v-if="currFlow === key">
            <el-tooltip
              effect="dark"
              :content="flowMap[key].desc"
              placement="right"
            >
              <i class="iconfont icon-question"></i>
            </el-tooltip>
          </div>
          <div class="open-btn" @click.stop>
            <el-switch
              v-if="!flowAxisStepIsSystem(key)"
              v-model="flowData.serviceEventTypeConfig.flowSetting[key].state"
            ></el-switch>
          </div>
        </div>
      </div>
    </div>

    <div class="setting-flow-main">
      <!-- 效果预览 -->
      <div class="setting-flow-preview-container" v-if="showFormPreview || showSatisfactionPreview">
        <div class="flow-preview-header">{{$t('common.base.preview1')}} <base-language-dropdown class="flow-preview-header-translate" v-if="showSetLanguage" :options="languagesList" :lang="formPreviewLocale" @change="changeLocale" /></div>
        <setting-flow-preview
          :type="currFlow"
          :fields="fields"
          :satisfaction-id="flowData.serviceEventTypeConfig.flowSetting[currFlow].questionId"
          :customer-satisfaction="customerSatisfaction"
          @onOpenFormDesignDialog="handleOpenFormDesignDialog"
          @openSetReviewQuestion="openSetReviewQuestion"
        ></setting-flow-preview>
      </div>

      <!-- 节点规则设置 -->
      <div class="setting-flow-specific-container">
        <div class="flow-specific-header">{{$t('event.setting.serviceEventTypeSetting.flow.steps.flowSettingPanel.des1')}}</div>
        <setting-flow-specific
          :type="currFlow"
          :flow-setting="flowData.serviceEventTypeConfig.flowSetting[currFlow]"
          :evaluation-options="evaluationOptions"
          :customer-satisfaction="customerSatisfaction"
          :event-type-id="serviceEventTypeId"
          @onOpenFormDesignDialog="handleOpenFormDesignDialog"
          @openSetReviewQuestion="openSetReviewQuestion"
        ></setting-flow-specific>
      </div>
    </div>


    <!-- 事件表单设置弹窗 -->
    <event-fields-setting
      ref="eventFormSettingRef"
      :mode="mode"
      :template-id="flowData.serviceEventTypeId"
      @success="refreshFields"
      :templateName="flowData.serviceEventTypeConfig.name"
    ></event-fields-setting>
  </div>
</template>

<script>
import { useLocaleProvide } from '@hooks/useLocale'
import { useFormMultiLanguage } from '@hooks/useFormMultiLanguage'
/** component*/
import SettingFlowPreview from '../components/SettingFlowPreview.vue';
import SettingFlowSpecific from '../components/SettingFlowSpecific.vue';
import EventFieldsSetting from '../eventFieldsSetting/EventFieldsSetting.vue';
import SetLanguage from '@src/modules/setting/serviceEvent/serviceEventTypeSetting/flow/components/SetLanguage.vue'
/** api*/
import * as SettingApi from '@src/api/SettingApi.ts';
import * as SettingServiceEventApi from '@src/api/SettingServiceEventApi';


/** until*/
import { cloneDeep, isEqual } from 'lodash';
import { FLOW_MAP } from '../../../constant';
import TableNameEnum from '@model/enum/TableNameEnum.ts';
import { getRootWindowInitData } from '@src/util/window'

const { isOpenMultiLanguage, languagesList } = useFormMultiLanguage()

import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

export default {
  name: 'flow-setting-panel',
  inject: ['flowData'],
  data() {
    return {
      flowMap: FLOW_MAP,
      currFlow: 'create', //  当前选择流程设置 key
      evaluationOptions: [], //  满意度方案选择参数
      fields: [], //  新建/回执 字段
      satisfiediFrameUrl:'',
      questionId: '',
    };
  },
  setup(){
    const { locale: formPreviewLocale, changeLocale } = useLocaleProvide('formPreviewLocale');

    return {
      formPreviewLocale,
      changeLocale,
      languagesList,
    };
  },
  computed: {
    mode() {
      return this.currFlow === 'finish'
        ? TableNameEnum.EventReceipt
        : TableNameEnum.Event;
    },
    /** 新建/回执表单*/
    showFormPreview() {
      return ['create', 'finish'].includes(this.currFlow);
    },
    serviceEventTypeId() {
      return this.flowData.serviceEventTypeId;
    },
    // 是否展示灰度满意度预览
    showSatisfactionPreview() {
      return ['evaluate'].includes(this.currFlow) && this.customerSatisfaction && this.flowData.serviceEventTypeConfig.flowSetting.evaluate.questionId;
    },
    // 灰度满意度方案
    customerSatisfaction() {
      return getRootWindowInitData()?.customerSatisfaction || false 
    },
    showSetLanguage(){
      return isOpenMultiLanguage && (this.currFlow == 'create' || this.currFlow == 'finish')
    }
  },
  watch: {
    serviceEventTypeId(id) {
      if(id) {
        // 初始表单字段
        if (this.showFormPreview) {
          this.getEventFields();
        }
      }

    }
  },
  methods: {
    /** 处理选择流程步骤*/
    handleSelectFlowStep(flowName) {
      this.currFlow = flowName;
      //  选择客户评价并且满意度方案未初始化时, 初始化满意度方案
      if (this.currFlow === 'evaluate' && !this.evaluationOptions.length && this.customerSatisfaction) {
        this.initEvaluationOptions();
      }
      //  选择新建/完成, 获取表单字段
      if (this.showFormPreview) {
        this.getEventFields();
      }
    },
    /** 打开表单设计器*/
    handleOpenFormDesignDialog() {
      this.$refs['eventFormSettingRef'].open();
    },

    /**  刷新表单字段*/
    refreshFields() {
      this.getEventFields();
    },

    /** 获取事件新建/回执表单字段*/
    async getEventFields() {
      try {
        const params = {
          tableName: this.currFlow === 'create' ? 'event' : 'eventReceipt',
          templateId: this.flowData.serviceEventTypeId || '',
          isFromSetting: false
        }
        const result = await SettingServiceEventApi.getEventTemplateFields(params);
        this.fields = result || [];

      } catch (error) {
        console.error(error)   
      }
    },

    /** 初始化满意度方案*/
    async initEvaluationOptions() {
      try {
        // 满意度方案初始化
        let res = await SettingApi.getUsedConfigList({});
        this.evaluationOptions = res.result || [];

      } catch (error) {
        console.error('fetch getUsedConfigList => err', error);
      }
    },

    /** 流程步骤是系统字段*/
    flowAxisStepIsSystem(key) {
      return this.flowMap[key].isSystem;
    },

    /** 流程步骤是关闭状态*/
    flowAxisStepIsClose(key) {
      return !this.flowData.serviceEventTypeConfig?.flowSetting[key].state;
    },
    /** 预览满意度方案*/    
    openSetReviewQuestion() {
      let flowSetting = this.flowData.serviceEventTypeConfig.flowSetting || {};
      let satisfactionId = flowSetting?.evaluate?.questionId;
      let fromId = window.frameElement.getAttribute('id');

      this.evaluationOptions.map(item=>{
        if(item.satisfactionId == satisfactionId) {
          this.questionId = item.id
        }
      })

      this.questionId ? openAccurateTab({
        type: PageRoutesTypeEnum.PageQuestionnaireSchemeEdit,
        key:this.questionId,
        reload: true,
        fromId
      }) : openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerExperienceQuestionnaireSchemeList,
        reload: true,
        fromId
      })
    },
  },
  components: {
    [SettingFlowPreview.name]: SettingFlowPreview,
    [SettingFlowSpecific.name]: SettingFlowSpecific,
    EventFieldsSetting,
    SetLanguage
  },
};
</script>

<style lang="scss" scoped>
.setting-flow-panel-container {
  padding: 0 12px 12px 12px;
  height: calc(100vh - 48px);
  min-height: calc(100vh - 48px);

  display: flex;
  // 流程线
  .setting-flow-axis-container {
    width: 298px;
    min-height: 100%;
    display: flex;
    flex-direction: column;
    .axis-header {
      width: 298px;
      height: 40px;
      background: #fafafa;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 14px;
      font-weight: 500;
      color: #262626;
      border-bottom: 1px solid #e8e8e8;
    }
    .setting-flow-axis {
      width: 298px;
      min-height: calc(100% - 40px);
      padding: 0px 16px;
      background: #ffffff;
      .flow-axis-step-box {
        position: relative;
        display: flex;
        justify-content: space-between;
        width: 100%;
        .tooltip-wrap {
          position: absolute;
          right: 44px;
          top: 40px;
          width: 20px;
          height: 20px;
          text-align: center;
          line-height: 20px;
          & > .iconfont {
            font-size: 14px;
            color: #8c8c8c;
          }
        }
        .open-btn {
          position: absolute;
          top: 40px;
          right: 0;
        }
        &:not(:last-child) {
          .flow-axis-step::after {
            content: '';
            position: absolute;
            left: 50%;
            bottom: -31px;
            display: block;
            transform: translateX(-50%);
            width: 1px;
            height: 30px;
            background: #e6e6e6;
          }
        }
        .flow-axis-step {
          display: flex;
          justify-content: space-between;
          cursor: pointer;
          position: relative;
          width: 188px;
          height: 44px;
          margin-top: 30px;
          padding: 10px;
          line-height: 22px;
          font-size: 14px;
          background: #ffffff;
          border-radius: 4px;
          border: 1px solid #d9d9d9;
          div:nth-child(1){
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
          }
          i {
            margin-right: 3px;
            color: $color-primary;
          }
          .open-tag {
            width: 52px;
            height: 22px;
            text-align: center;
            color: #67c23a;
            background: #e1f3d8;
            border-radius: 11px;
            border: 1px solid #cfedc0;
            font-size: 12px;
          }
          &.disabled {
            color: #999999;
            background: #f2f2f2;
            border: 1px solid #e6e6e6;
            i {
              color: #999999;
            }
          }
          &.active {
            background: $color-primary-light-1 !important;
            border: 1px solid $color-primary !important;
          }
        }
        &.close {
          color: #8c8c8c;
          .flow-axis-step {
            background: #f2f2f2;
            border: 1px solid #e6e6e6;
            color: #999;
            .iconfont {
              color: #bfbfbf;
            }
            .open-tag {
              background: #e6e6e6;
              color: #8c8c8c;
              border: 1px solid #d9d9d9;
            }
          }
        }
      }
    }
  }

  .setting-flow-preview-container {
    flex: 1;
    height: 100%;
    display: flex;
    flex-direction: column;
    margin-right: 12px;
    .flow-preview-header {
      width: 100%;
      height: 40px;
      background: #fafafa;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 14px;
      font-weight: 500;
      color: #262626;
      border-bottom: 1px solid #e8e8e8;
      position: relative;
      
      &-translate{
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        font-size: 12px;
      }
    }
  }
   .setting-flow-main {
      flex: 1;
      min-height: 100%;
      padding-left: 12px;
      width: 100%;
      display: flex;
   }
  .setting-flow-specific-container {
    min-width: 430px;
    min-height: 100%;
    display: flex;
    flex-direction: column;
    flex: 1;
    .flow-specific-header {
      width: 100%;
      height: 40px;
      background: #fafafa;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 14px;
      font-weight: 500;
      color: #262626;
      border-bottom: 1px solid #e8e8e8;
    }
  }
}
</style>
